//mysal数据连接类//
package Operation;
import java.sql.*;
import java.util.*;
import User.*;
public class jdbc {
    private String path;//数据库地址及设置
    private String id;//数据库账号
    private  String password;//数据库密码
    Connection con;//连接对象
    Statement state;//执行对象
    public jdbc(String path, String id, String password) {
        //注册数据库驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        this.path = path;
        this.id = id;
        this.password = password;
        dataBase();
    }
    public void dataBase(){
        //获取连接对象
        try {
            this.con = DriverManager.getConnection( this.path, this.id, this.password);
            //获取执行对象
            this.state = this.con.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //执行SQL语句(查询之外)
    public void sql(String str){
        try {
            boolean execute = this.state.execute(str);
            if(execute){
                System.out.println("执行失败");
            }else{
                System.out.println("执行成功.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     //执行查询管理员表
    public ArrayList<administrators> search_adminstrators_Message(){
        ArrayList<administrators> administrators_array = new ArrayList<>();

        try {
            String str = "select * from administrators";
            //获取结果集
            ResultSet resultSet1 = this.state.executeQuery(str);
            while (resultSet1.next()){
                administrators message = new administrators(resultSet1.getString("mgname"),resultSet1.getString("mgaccount"),resultSet1.getString("mgpassword") );
                administrators_array.add(message);
            }

            return administrators_array;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //执行查询用户表
    public ArrayList<commonuser> search_users_Message(){

        ArrayList<commonuser> users_array = new ArrayList<>();
        try {
           String str = "select * from users";
            //获取结果集
            ResultSet resultSet2 = this.state.executeQuery(str);
            while (resultSet2.next()){
                commonuser message = new commonuser(resultSet2.getString("uname"),resultSet2.getString("uaccount"),resultSet2.getString("upassword") );
                users_array.add(message);
            }

            return users_array;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
